package com.sdgakj.web.feed;

import com.alibaba.fastjson.JSONObject;
import com.sdgakj.dto.CommentDetailDTO;
import com.sdgakj.dto.base.ResCode;
import com.sdgakj.dto.base.ResResult;
import com.sdgakj.entity.CommonReview;
import com.sdgakj.entity.Feed;
import com.sdgakj.entity.FeedComment;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.enums.EnumReviewType;
import com.sdgakj.service.ServiceException;
import com.sdgakj.service.account.ShiroDbRealm.ShiroUser;
import com.sdgakj.service.commonReport.CommonReviewService;
import com.sdgakj.service.feed.FeedService;
import com.sdgakj.service.feed.FeedTagService;
import com.sdgakj.service.user.UserService;
import com.sdgakj.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.ServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/feed")
public class FeedController {
	
	private static Logger logger = LoggerFactory.getLogger(FeedController.class);

	private static final String PAGE_SIZE = "10";
    private static final String CREATE="create";
    private static final String UPDATE="update";
    private static final String RESULT_TRUE="true";
    private static final String RESULT_FALSE="false";
	
	@Autowired
	private FeedService feedService;
	
	@Autowired
	private FeedTagService feedTagService;
	
	@Autowired
	private CommonReviewService reviewService;

	@Autowired
	private UserService userService;
	/**
	 * 列表
	 * @param pageNumber 页号
	 * @param pageSize   每页大小
	 * @param sortType   排序字段
	 * @param model			
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model,
			ServletRequest request) {
		logger.info("查询贴子信息列表...");
		Map<String,Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		if(searchParams.get("GTE_createDate")!=null){
			searchParams.put("GTE_createDate", com.sdgakj.utils.DateUtil
					.formatStringToDate(searchParams.get("GTE_createDate") + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
		}
		if (searchParams.get("LTE_createDate") != null ) {
			searchParams.put("LTE_createDate", com.sdgakj.utils.DateUtil
					.formatStringToDate(searchParams.get("LTE_createDate") + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
		}
		// 判断评论数和点赞数
		if(searchParams.get("GTE_commentCount")!=null && StringUtils.isNotBlank(searchParams.get("GTE_commentCount").toString())){
			searchParams.put("GTE_commentCount",Integer.parseInt(searchParams.get("GTE_commentCount").toString().trim()));
		}
		if(searchParams.get("LTE_commentCount")!=null && StringUtils.isNotBlank(searchParams.get("LTE_commentCount").toString())){
			searchParams.put("LTE_commentCount", Integer.parseInt(searchParams.get("LTE_commentCount").toString().trim()));
		}
		if(searchParams.get("GTE_likeCount")!=null && StringUtils.isNotBlank(searchParams.get("GTE_likeCount").toString().trim())){
			searchParams.put("GTE_likeCount", Integer.parseInt(searchParams.get("GTE_likeCount").toString().trim()));
		}
		if(searchParams.get("LTE_likeCount")!=null && StringUtils.isNotBlank(searchParams.get("LTE_likeCount").toString().trim())){
			searchParams.put("LTE_likeCount", Integer.parseInt(searchParams.get("LTE_likeCount").toString().trim()));
		}
		if(searchParams.get("EQ_reportCount")!=null && StringUtils.isNotBlank(searchParams.get("EQ_reportCount").toString().trim())){
			if(StringUtils.equals(searchParams.get("EQ_reportCount").toString(), "0")){
				searchParams.put("EQ_reportCount", searchParams.get("EQ_reportCount"));
			}else if(StringUtils.equals(searchParams.get("EQ_reportCount").toString(), "1")){
				searchParams.put("GTE_reportCount", searchParams.get("EQ_reportCount"));
				searchParams.remove("EQ_reportCount");
			}
		}
		Page<Feed> feeds = feedService.getFeedByPage(searchParams, pageNumber, pageSize, "id", sortType);
		if (searchParams.get("GTE_createDate") != null) {
			searchParams.put("GTE_createDate",
					DateUtil.formatDateToString((Date) searchParams.get("GTE_createDate"), "yyyy-MM-dd"));
		} else {
			searchParams.put("GTE_createDate", "");
		}
		if (searchParams.get("LTE_createDate") != null && searchParams.get("LTE_createDate").toString().trim()!="null") {
			searchParams.put("LTE_createDate",
					DateUtil.formatDateToString((Date) searchParams.get("LTE_createDate"), "yyyy-MM-dd"));
		}else {
			searchParams.put("LTE_createDate", "");
		}
		if(searchParams.get("EQ_reportCount")!=null && StringUtils.isNoneBlank(searchParams.get("EQ_reportCount").toString())){
			searchParams.put("EQ_reportCount", "0");
		}
		if(searchParams.get("GTE_reportCount")!=null){
			searchParams.put("EQ_reportCount", "1");
		}
		model.addAttribute("feeds",feeds);
		model.addAttribute("sortType", sortType);
		model.addAttribute("feedtags",feedTagService.getFeedTagAllByState(EnumReviewType.PUBLISH.getCode()));
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "feed/feedList";
	}
	
	/**
	 * 跳转添加页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="create",method=RequestMethod.GET)
	public String  create(Model model){
		model.addAttribute("action", "create");
		// 标签列表
		model.addAttribute("feedtags",feedTagService.getFeedTagAllByState(EnumReviewType.PUBLISH.getCode()));
		return "feed/feedForm";
	}
	
	@RequestMapping(value="create",method=RequestMethod.POST)
	public String createFeedTag(Feed entity,String tag,String loginName,RedirectAttributes redirectAttributes){
		entity.setFeedTag(feedTagService.getFeedTagById(Long.valueOf(tag)));
		feedService.createFeed(entity,loginName);
		return "redirect:/feed/list";
	}
	
	/**
	 * 跳转修改页面
	 * @return
	 */
	@RequestMapping(value="update/{id}",method=RequestMethod.GET)
	public String update(@PathVariable("id") Long id, Model model){
		model.addAttribute("feed", feedService.getFeedById(id));
		model.addAttribute("action", "update");
		
		return "feed/feedForm";
	}
	
	@RequestMapping(value="update",method=RequestMethod.POST)
	public String updateInsurances( @ModelAttribute("model")Feed entity,RedirectAttributes redirectAttributes){
		entity.setUpdateDate(new Date());
		entity.setContent(StringUtils.replace(entity.getContent(), " ", ""));
		feedService.updateFeed(entity);
		redirectAttributes.addFlashAttribute("message", "更新成功");
		return "redirect:/feedtag/list";
	}
	
	
	@RequestMapping(value="/delete/{id}",method=RequestMethod.GET)
	public String delete(@PathVariable("id") Long id,RedirectAttributes redirectAttributes){
		Feed feed = feedService.getFeedById(id);
//		feed.setState(EnumIsDelete.DELETED.getCode());
		feed.setDeltag(EnumIsDelete.DELETED.getCode());
		feedService.deleteFeed(id);
		redirectAttributes.addFlashAttribute("message", "删除信息成功！");
		return "redirect:/feed/list";
	}
	
	/**
	 * 查看贴子详情
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getDetailFeed/{id}",method=RequestMethod.GET)
	public String getDetailFeed(@PathVariable("id")Long id,Model model){
		Feed feed =feedService.getFeedById(id);
		List<CommonReview> reviewList =reviewService.getReviewFeed(id);//查看是否有贴子
		if(!CollectionUtils.isEmpty(reviewList) && reviewList.size()>0){
			model.addAttribute("delfeed",reviewList.get(0)); //获取管理员删除的帖子信息
		}else{
			model.addAttribute("delfeed",null); //获取管理员删除的帖子信息
		}
		List<CommentDetailDTO> list =reviewService.findReviewByFeedId(id);
		model.addAttribute("commentlist", list);// 评论的列表
		model.addAttribute("feed",feed);
		return "feed/feedDetailForm";
	}
	
	/**查询发帖列表*/
	@RequestMapping(value="/getfeedlist",method = RequestMethod.GET)
	@ResponseBody
	public Page<FeedComment> getFeed(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "pagesize", defaultValue = "20") int pageSize,
			@RequestParam(value="feedId",required=false,defaultValue="0")Long feedId,
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model,
			ServletRequest request) {
		logger.info("W-[查询发帖评论列表...]");
		Page<FeedComment> commentList =feedService.findPageComment(feedId, pageNumber, pageSize);
		return commentList;
	}
	/**查询点赞列表*/
	@RequestMapping(value="/getlikelist",method = RequestMethod.GET)
	@ResponseBody
	public Page<Object[]> getFeedLikeList(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "pagesize", defaultValue = "20") int pageSize,
			@RequestParam(value="feedId",required=false,defaultValue="0")Long feedId,
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
			ServletRequest request) {
		logger.info("W-[查询点赞...]");
		Page<Object[]> likeList =feedService.findPageLikeLoginName(feedId, pageNumber, pageSize);
		return likeList;
	}

	@ModelAttribute
	public void getFeedTag(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		if (id != -1) {
			model.addAttribute("model", feedService.getFeedById(id));
		}
	}
	
	/**
	 * ajax删除帖子
	 * id : 贴子信息id
	 * reason： 删除原因
	 * @return
	 */
	@RequestMapping(value="deletefeed",method=RequestMethod.POST)
	@ResponseBody
	public ResResult deleteFeed(final Long id,final String reason){
		ResResult result =new ResResult();
		try{
			Feed feed =feedService.getFeedById(id);
			feed.setDeltag(EnumIsDelete.DELETED.getCode());
			feedService.deleteFeed(id);
			new Runnable(){
				@Override
				public void run() {
	                ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
					CommonReview entity =new CommonReview();
					entity.setUserId(shiroUser.id);
					entity.setNote(reason);
					entity.setTargetId(id);
					entity.setType(EnumReviewType.FEED.getCode());
					entity.setCustomerId(feedService.getFeedById(id).getUserId());
					entity.setCreateDate(new Date());
					reviewService.saveReview(entity);
				}
				
			}.run();
		}catch(ServiceException e){
			result.setResCode(e.getResCode());
			logger.info("W-[删除帖子]业务错误");
		}catch(Exception e){
			result.setResCode(ResCode.ERROR);
			logger.error("W-[删除帖子]程序异常");
		}
		return result;
	}
	
	/**
	 * ajax删除评论
	 * id : 评论id
	 * reason： 删除原因
	 * @return
	 */
	@RequestMapping(value="deletecomment",method=RequestMethod.POST)
	@ResponseBody
	public ResResult deleteComment(final Long id,final String reason){
		ResResult result =new ResResult();
		try{
			final FeedComment comment =feedService.deleteFeedComment(id);
			new Runnable(){
				@Override
				public void run() {
	                ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
					CommonReview entity =new CommonReview();
					entity.setUserId(shiroUser.id);
					entity.setNote(reason);
					entity.setTargetId(id);
					entity.setType(EnumReviewType.FEEDCOMMENT.getCode());
					entity.setCustomerId(feedService.getFeedById(id).getUserId());
					entity.setCreateDate(new Date());
					reviewService.saveReview(entity);
				}
				
			}.run();
		}catch(ServiceException e){
			result.setResCode(e.getResCode());
			logger.info("W-[删除帖子]业务错误");
		}catch(Exception e){
			result.setResCode(ResCode.ERROR);
			logger.error("W-[删除帖子]程序异常");
		}
		return result;
	}
	/**
	 * 校验是否唯一
	 * @param type{create update}
	 */
	@RequestMapping(value = "/ajaxcheck")
	@ResponseBody
	public String checkName(@RequestParam("title") String title,@RequestParam(value = "op") String type,@RequestParam(value = "id", defaultValue = "0")Long id) {
		List<Feed>  list = null;
		if(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(title)){
			list = feedService.getFeedByName(title);
		}else{
			return RESULT_FALSE;
		}
		if(list!=null && list.size()>0){
			if(type.equals(CREATE)){
				return "false";
			}else if(type.equals(UPDATE)){
				if(list.size()>1){
					return RESULT_FALSE;
				}else{
					if(list.get(0).getId().equals(id)){
						return RESULT_TRUE;
					}else{
						return RESULT_FALSE;
					}
				}
			}else{
				return RESULT_FALSE;
			}
		}else{
			return RESULT_TRUE;
		}
	}
	
	/**
     * 置顶和取消置顶
     *
     * @param id
     * @param top
     * @return
     */
    @RequestMapping(value = "setTop", method = RequestMethod.POST)
    @ResponseBody
    public ResResult setTop(@RequestParam(value = "id") Long id, @RequestParam(value = "top") Boolean top) {
        ResResult result = new ResResult(ResResult.WEB_MODEL);
        try {
        	feedService.setTop(id, top);
        } catch(ServiceException e){
			result.setResCode(e.getResCode());
			logger.info("W-[置顶帖子]业务错误");
		} catch(Exception e){
			result.setResCode(ResCode.ERROR);
			logger.error("W-[置顶帖子]程序异常");
		}
        return result;
    }

	/**
	 * 点赞
	 * */
	@RequestMapping(value = "/createlike",method = RequestMethod.POST)
	public JSONObject createLike(@RequestParam(value = "userId",required = true,defaultValue = "1") Long userId,
								 @RequestParam(value = "feedId",required = true) Long feedId
								/* @RequestParam(value = "likeCount",required = false) Long likeCount*/){
		JSONObject request=new JSONObject();
		try {
			feedService.createLike(userId, feedId);
			request.put("mess","点赞成功！");
		}catch (Exception e){
			request.put("mess","点赞失败！");
		}
		return  request;
	}
	/**
	 * 取消点赞
	 * */
	@RequestMapping(value = "delLike")
	public JSONObject delLike(@RequestParam(value = "userId") Long userId,
							  @RequestParam(value = "feedId") Long feedId){
		JSONObject request=new JSONObject();
		try{
			feedService.delLike(userId,feedId);
			request.put("mess","取消成功！");
		}catch (Exception e){
			request.put("msg","取消失败！");
		}
		return request;
	}
}
